using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using System.Text;

namespace Wsp365.MobileAccess.Features.RedirectWelcomePage
{
    [Guid("8fa8b043-c764-4753-83c6-90c4340680ef")]
    public class RedirectWelcomePageEventReceiver : SPFeatureReceiver
    {
        private static readonly string WSP365_WELCOMEPAGE_KEY = "wsp365.welcomepage";
        private static readonly string WSP365_REDIRPAGE = @"<%@ Assembly Name=""Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c""%> <%@ Page Language=""C#"" %>
            <%@ Register Tagprefix=""SharePoint"" Namespace=""Microsoft.SharePoint.WebControls"" Assembly=""Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"" %>
            <SharePoint:UrlRedirector runat=""server"" id=""UrlRedirector"" />";

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPWeb web = (SPWeb)properties.Feature.Parent;
            SPFolder rootFolder = web.RootFolder;  
            string welcomePage = (rootFolder.Properties["vti_welcomepage"] as string)??"default.aspx";
            string redirectionPage = "wsp365/redir/?mobile=0";
            if (welcomePage != redirectionPage)
            {
                if (!web.AllProperties.ContainsKey(WSP365_WELCOMEPAGE_KEY))
                {
                    web.AddProperty(WSP365_WELCOMEPAGE_KEY, welcomePage);
                    web.Update();
                }
                rootFolder.SetProperty("vti_welcomepage", redirectionPage);
                rootFolder.Update();
            }

            SPDocumentLibrary list = (SPDocumentLibrary)web.Lists["Wsp365.RedirDocLib"];
            list.Fields.Add(web.Site.RootWeb.Fields[SPBuiltInFieldId.URL]);
            SPFile file = list.RootFolder.Files.Add("default.aspx", ASCIIEncoding.ASCII.GetBytes(WSP365_REDIRPAGE));
            SPFieldUrlValue fieldUrl = new SPFieldUrlValue();
            fieldUrl.Url = GetWebRelativeUrl(web) + welcomePage + "?mobile=0";
            file.Item[SPBuiltInFieldId.URL] = fieldUrl;
            file.Item.Update();
            //Set AnonymousPermMask64
            
            if (!list.HasUniqueRoleAssignments)
            {
                list.BreakRoleInheritance(true);
            }
            list.AnonymousPermMask64 = SPBasePermissions.OpenItems;
            list.Update();
            list.AnonymousPermMask64 =
              (SPBasePermissions.Open |
               SPBasePermissions.OpenItems |
               SPBasePermissions.ViewFormPages |
               SPBasePermissions.ViewListItems);
            list.Update();
            Wsp365.MobileAccess.UpdateNavigationEventReceiver.UpdateNavigationEventReceiver.FixMobileNavigation(web);
        }



        private string GetWebRelativeUrl(SPWeb web)
        {

            if (web.ServerRelativeUrl[web.ServerRelativeUrl.Length - 1] == '/')
            {
                return web.ServerRelativeUrl;
            }
            else
            {
                return web.ServerRelativeUrl + "/";
            }
        }
        
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPWeb web = (SPWeb)properties.Feature.Parent;
            SPFolder rootFolder = web.RootFolder;
            string welcomePage = "Pages/default.aspx"; ;
            if (web.AllProperties.ContainsKey(WSP365_WELCOMEPAGE_KEY))
            {
                welcomePage = web.GetProperty(WSP365_WELCOMEPAGE_KEY) as string;
                web.DeleteProperty(WSP365_WELCOMEPAGE_KEY);
                web.Update();
            }
            rootFolder.SetProperty("vti_welcomepage", welcomePage);
            rootFolder.Update();
            SPDocumentLibrary list = (SPDocumentLibrary)web.Lists["Wsp365.RedirDocLib"];
            list.Delete();
        }
    }
}
